#include "mystdio.h"

MYFILE* BuyFile(int fd, int flag)
{
    MYFILE* myfile = (MYFILE*)malloc(sizeof(MYFILE));
    myfile->fileno = fd;
    myfile->flag = flag;
    myfile->bufflen = 0;
    myfile->flush_buff = LINE_FLUSH;
    //初始化缓冲区
    memset(myfile->outbuff, 0, sizeof(myfile->outbuff));
    return myfile;
}
MYFILE* MyOpen(const char* pathname, const char* mode)
{
    //确定文件的打开方式
    int fd = -1;
    int flag = 0;
    if(strcmp(mode, "w") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(pathname, flag, 0666);
    }
    else if(strcmp(mode, "a") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_APPEND;
        fd = open(pathname, flag, 0666);
    }
    else if(strcmp(mode, "r"))
    {
        flag = O_RDONLY;
        fd = open(pathname, flag);
    }
    else{
        //???
    }
    if(fd < 0) return NULL;//打开文件失败
    return BuyFile(fd,flag);
}
void MyClose(MYFILE* file)
{
    if(file == NULL) return;
    if(file->fileno < 0) return;
    MyFlush(file);
    close(file->fileno);
    free(file);
}
int MyWrite(MYFILE* file, void* str, int len)
{
    //将数据拷贝到缓冲区当中
    //int n = 0;
    if(file->bufflen + len > MAX)
    {
        //n = MAX - file->bufflen;
        //memcpy(file->outbuff + file->bufflen, str, n);
        //MyFlush(file);
        MyFlush(file);
    }
    //memcpy(file->outbuff + file->bufflen,(void*)((char*)str + n), strlen((char*)str) - n);
    memcpy(file->outbuff + file->bufflen,str,len);
    file->bufflen += len;
    if(file->flush_buff & NONE_FLUSH)//无缓冲
        MyFlush(file);
    else if((file->flush_buff & LINE_FLUSH) && (file->outbuff[file->bufflen-1] == '\n' || file->bufflen == MAX))//行缓冲
        MyFlush(file);
    else if((file->flush_buff & FULL_FLUSH) && (file->bufflen == MAX))//全缓冲
        MyFlush(file);
    return 0;
}
void MyFlush(MYFILE* file)
{
    if(file->bufflen <= 0)  return;
    write(file->fileno, file->outbuff, file->bufflen);
    file->bufflen = 0;
    fsync(file->fileno);
}
